const db = require('db/car.js');
const common = require('lib/utils/common.js');
const dbRecord = require('db/record.js');
const xlsx = require('node-xlsx');
const dbBlackList = require('db/blackList.js');

/** @name 车辆列表 **/
exports.list = async ctx => {
	const { number, realname, phone, status } = ctx.query;
	const options = {
		...common.YD_getPageDefault(ctx),
		number, realname, status, phone
	}
	const totalRes = await db.yd_count(options);
  const total = totalRes[0].count || 0;
	// 黑名单
	const blackList = await dbBlackList.yd_listAll();
	const blackCarList = blackList.map(car => car.number);

  const rows = await db.yd_list(options);
	ctx.success({
    total,
    rows: rows.map(item => ({ ...item, isBlack: blackCarList.includes(item.number) }))
  });
};

/** @name 编辑车辆 **/
exports.edit = async ctx => {
	if(ctx.requiredParams(['id', 'number'])) return;
	const { id, number, color, images, note } = ctx.request.body;
	const currentTime = common.YD_dateFormat()
	const options = {
		number,
		color,
		images,
		note,
		updateTime: currentTime,
	}
	await db.yd_update(options, { number });
	ctx.success('车辆编辑成功');
};

/** @name 设置车辆出库 **/
exports.status = async ctx => {
	if(ctx.requiredParams(['id', 'number', 'status'])) return;
	const { id, number, status } = ctx.request.body;
	const options = {
		status,
		updateTime: common.YD_dateFormat(),
	}

	// 同步停车次数
	const result = await db.yd_find({ number });
	const firstItem = result[0];
	options.count = firstItem.count + 1;

	// 同步进出记录
	const recordResult = await dbRecord.yd_find({ number });
	const recordItem = recordResult[0];
	await dbRecord.yd_update({ status: 1 }, { id: recordItem.id });

	await db.yd_update(options, { number });
	ctx.success('设置成功');
};

/** @name 导出车辆信息 **/
exports.export = async ctx => {
	// excel相关
	const header = ['车牌号码', '用户名称', '联系电话', '停车次数', '车辆颜色', '备注'];
	const keys = ['number', 'realname', 'phone', 'count', 'color', 'note'];

	// 拉取数据库数据
	const rows = await db.yd_export();

	// 数据处理
	const body = [];
	let bodyItem = [];
	rows.forEach(item => {
		keys.forEach(key => {
			bodyItem.push(item[key]);
		})
		body.push(bodyItem);
		bodyItem = [];
	})

	// 完整excel数据
	const data = [header, ...body];
	console.log('data', data)
	const buffer = xlsx.build([{name: 'sheet1', data: data}]);
	const filename = encodeURI(`${common.YD_dateFormat('empty')}-车辆信息.xlsx`);
	//设置响应头
	ctx.set('Content-Type', 'application/vnd.openxmlformats');
	ctx.set('Content-Disposition', 'attachment; filename=' + filename);
	//返回结果
	ctx.body = buffer;
};

/** @name 绑定车主 **/
exports.bind = async ctx => {
	if(ctx.requiredParams(['id', 'userId'])) return;
	const { id, userId } = ctx.request.body;
	const options = {
		userId,
		updateTime: common.YD_dateFormat(),
	}

	await db.yd_updateId(options, { id });
	ctx.success('设置成功');
};

/** @name 加入黑名单 **/
exports.addBlackList = async ctx => {
	if(ctx.requiredParams(['number', 'note'])) return;
	const { number, userId, note } = ctx.request.body;
	const currentTime = common.YD_dateFormat()
	const options = {
		number,
		userId,
		note,
		createTime: currentTime,
		updateTime: currentTime,
	}
	await dbBlackList.yd_add(options);
	ctx.success('黑名单添加成功');
};
